<template>
  <a-modal
    @close="reset"
    :title="t['新增']"
    width="700px"
    :footer="false"
    v-model:visible="visible"
  >
    <a-card v-if="form">
      <a-form :model="form" layout="vertical" ref="formRef" @submit-success="submit" :rules="rules">
        <a-form-item field="name" :label="t['名称']">
          <a-input allow-clear v-model="form.name"></a-input>
        </a-form-item>

        <a-form-item field="num" :label="t['联屏数量']">
          <a-select allow-clear :options="numOptions" v-model="form.num"></a-select>
        </a-form-item>

        <a-form-item field="name" :help="t['素材要和联屏数量相同']" :label="t['选择联屏素材']">
          <ul class="card-list" ref="listRef">
            <li v-for="(item, index) in fileList" :key="item.link">
              <Resource :file="renderResource(item)" />
              <div class="close-icon" @click.stop="del(index)">
                <icon-close />
              </div>
              <a-badge :count="index + 1" class="index"></a-badge>
            </li>
            <li
              class="center cursor-pointer no-drag"
              @click="selectFile"
              v-if="fileList.length !== form.num"
            >
              <icon-plus />
            </li>
          </ul>
        </a-form-item>

        <a-row>
          <a-col>
            <div class="flex justify-center gap-2">
              <a-button type="primary" :disabled="fileList.length !== form.num" htmlType="submit">
                {{ t["确定"] }}
              </a-button>
              <a-button @click="visible = false">{{ t["取消"] }}</a-button>
            </div>
          </a-col>
        </a-row>
      </a-form>

      <FileSelector
        @change="onSelected"
        :limit="form.num"
        :selected="rowList"
        v-model:visible="displayFileSelector"
        multiple
        type="1"
      />
    </a-card>
  </a-modal>
</template>

<script setup lang="ts">
import { Library } from "@/api/service/library/types";
import { FieldRule } from "@arco-design/web-vue";

import { addCross, Cross, CrossResource, updateCross } from "@/api/service/lcd-device/cross";
// @ts-ignore
import FileSelector from "../../../components/file-selector/FileSelector.vue";

const t = translate("公共模块");

const formRef = ref();

const form = defineModel<Cross>("form");

const visible = defineModel<boolean>();

const displayFileSelector = ref(false);

const emit = defineEmits(["submit"]);

const fileList = ref<CrossResource[]>([]);

const rowList = ref<Library[]>([]);

const numOptions = Array.from({ length: 4 }).map((v, i) => {
  return {
    label: `${i + 2}`,
    value: i + 2
  };
});

const reset = () => {
  formRef.value?.resetFields();
  fileList.value = [];
};

const submit = async () => {
  if (!form.value) return;
  if (!form.value.id) {
    await addCross({
      ...form.value!,
      resource: fileList.value
    });
  } else {
    await updateCross({
      ...form.value!,
      resource: fileList.value
    });
  }

  visible.value = false;
  reset();
  emit("submit");
};

const selectFile = () => {
  displayFileSelector.value = true;
};

const rules: Record<string, FieldRule[]> = {
  name: [{ required: true, message: t.value["请输入名称"] }]
};

const onSelected = (files: Library[]) => {
  rowList.value = [...files];
  fileList.value = [...files].map((v) => {
    const [w, h] = v.sizeDesc.split("*");
    return {
      link: v.uri,
      width: Number(w),
      height: Number(h),
      size: v.bytes,
      md5: v.md5,
      offsetX: 0,
      offsetY: 0,
      type: v.type
    };
  });
};

const renderResource = (item: CrossResource): Partial<Library> => {
  return {
    uri: item.link,
    sizeDesc: `${item.width}*${item.height}`,
    bytes: item.size,
    type: item.type
  };
};

const del = (index: number) => {
  fileList.value?.splice(index, 1);
  rowList.value.splice(index, 1);
};

watch(
  () => form.value?.resource,
  () => {
    fileList.value = form.value?.resource || [];
  },
  {
    deep: true
  }
);
</script>

<style lang="scss" scoped>
.card-list {
  @apply grid grid-cols-4 w-full gap-2;
  li {
    border: 1px solid gray;
    position: relative;
    @apply h-[120px] w-full;
  }
  .drag-hand {
    @apply h-[20px] w-[20px] absolute top-1 left-1 bg-gray-200  center select-none;
  }
  .close-icon {
    @apply right-0 top-0 absolute bg-red text-white w-[20px] h-[20px] center select-none cursor-pointer;
  }
  .index {
    @apply left-1 bottom-1 absolute;
  }
}
</style>
